package at.jku.se.fastsell.rest.client.test;

import java.util.List;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Response;

import at.jku.se.fastsell.rest.AuctionJSON;

import com.owlike.genson.GenericType;
import com.owlike.genson.Genson;

public class RestClient {

	public static void main(String[] args) {
		try {
			checkUser("user1", "pwd2");
		} catch (ServiceException e) {
			e.printStackTrace();
		}

	}
	
	public static List<AuctionJSON> retrieveAllAuctions() throws ServiceException {
		try {
			Client client = ClientBuilder.newClient();
			WebTarget target = client.target("http://localhost:8080/FastSell/rest/auctions/");

			Response r = target.request("application/json").get();
			String result = r.readEntity(String.class);

			Genson g = new Genson();
			return g.deserialize(result, new GenericType<List<AuctionJSON>>() {});
		} catch (Exception e) {
			throw new ServiceException("Could not retrieve auctions", e);
		}
	}
	
	public static boolean checkUser(String username, String password) throws ServiceException {
		try {
			Client client = ClientBuilder.newClient();
			WebTarget target = client.target("http://localhost:8080/FastSell/rest/users/{username}/verify?password={password}");
		
			Response r = target.resolveTemplate("username", username).resolveTemplate("password", password).request().get();
			r.close();
			
			if (r.getStatus() == 200) {
				return true;
			}
		} catch (Exception e) {
			throw new ServiceException("Error in checking user", e);
		}
		return false;
	}

}
